#include "usermodel.hpp"
#include "db.hpp"
#include <muduo/base/Logging.h>

static std::string server = "127.0.0.1";
static std::string dbuser = "root";
static std::string dbpwd = "123456";
static std::string dbname = "chat";

bool UserModel::insert(User &user)
{
    char sql[1024] = { 0 };
    sprintf(sql, "insert into user(name, password, state) values('%s', '%s', '%s')",
        user.getName().c_str(), user.getPwd().c_str(), user.getState().c_str());

    MySQL mysql;
    if (mysql.connect(server, dbuser, dbpwd, dbname)) {
        if (mysql.update(sql)) {
            user.setId(mysql_insert_id(mysql.getConnection()));
            return true;
        }
    }

    return false;
}

User UserModel::query(int id)
{
    char sql[1024] = { 0 };
    MYSQL_RES *res;
    MySQL mysql;
    MYSQL_ROW row;
    User user;

    do {
        res = nullptr;
        row = nullptr;
        sprintf(sql, "select * from user where id = %d", id);
        if (mysql.connect(server, dbuser, dbpwd, dbname)) {
            res = mysql.query(sql);
            if (!res) {
                LOG_ERROR << "failed to query user " << id;
                break;
            }
            row = mysql_fetch_row(res);
            if (row == nullptr) {
                break;
            }
            user.setId(atoi(row[0]));
            user.setName(row[1]);
            user.setPwd(row[2]);
            user.setState(row[3]);
        }
    } while (0);
    if (res) {
        mysql_free_result(res);
    }
 
    return user;
}

bool UserModel::updateState(User &user)
{
    char sql[1024] = { 0 };
    MySQL mysql;
    bool ret;
    do {
        ret = false;
        sprintf(sql, "update user set state = '%s' where id = %d", user.getState().c_str(), user.getId());
        if (!mysql.connect(server, dbuser, dbpwd, dbname)) {
            LOG_ERROR << "failed to connect db ";
            break;
        }
        if (!mysql.update(sql)) {
            LOG_ERROR << "failed to update user " << user.getName() << " state";
            break;
        }
        ret = true;
    } while (0);

    return ret;
}

void UserModel::resetState()
{
    char sql[1024] = { 0 };
    MySQL mysql;
    
    do {
        sprintf(sql, "update user set state = 'offline' where state = 'online'");
        if (!mysql.connect(server, dbuser, dbpwd, dbname)) {
            LOG_ERROR << "failed to connect db ";
            break;
        }
        if (!mysql.update(sql)) {
            LOG_ERROR << "failed to update users state to offline";
            break;
        }
    } while (0);
}